<!--
 * @Author: aster lipian1004@163.com
 * @Date: 2025-02-20 17:08:40
 * @FilePath: \aster-flowable-uniapp\src\components\form\render\associated-property.vue
 * @Description: 关联属性
 * Copyright (c) 2025 by Aster, All Rights Reserved.
-->
<template>
  <van-field
    v-if="!_hidden"
    :model-value="_value"
    :name="formItemProp"
    placeholder=""
    :readonly="true"
    :required="_required"
    :rules="_rules"
    :input-align="FieldInputAlignEnum.RIGHT"
    :error-message-align="FieldInputAlignEnum.RIGHT"
    :label-width="showLabel ? '' : '5rpx'"
  >
    <template #label>
      <text v-if="showLabel">{{ formItem.title }}</text>
    </template>
    <form-design-render
      v-if="
        isNotEmpty(formItem.props.associatedForm.formCode) &&
        isNotEmpty(formItem.props.associatedField)
      "
      v-model:value="_value"
      :form-item="_associatedFormItem"
      :form-data="_associatedFormData"
      :mode="mode"
      :show-label="false"
    />
  </van-field>
</template>
<script setup lang="ts">
  import { evaluateFormula, flatFormItems } from '@/utils/workflow';
  import { computed, PropType, ref, watch } from 'vue';
  import { isNotEmpty, isObject } from '@/utils/is';
  import { FormPermissionEnum } from '@/enums/workFlowEnum';
  import { FieldInputAlignEnum } from '@/enums/formEnum';
  import { instanceInfoByInstanceIdApi } from '@/api/workflow/task';
  import { ResultEnum } from '@/enums/httpEnum';
  import FormDesignRender from '@/components/form/form-design-render.vue';

  const emit = defineEmits(['update:value']);
  const props = defineProps({
    value: {
      type: String,
      default: '',
    },
    mode: {
      type: String as PropType<'design' | 'form' | 'search' | 'table' | 'print'>,
      default: 'design',
    },
    formData: {
      type: Object as PropType<WorkForm.FormDataModel>,
      default: {},
    },
    formItem: {
      type: Object as PropType<WorkComponent.ComponentConfig>,
      default: {},
    },
    tableId: {
      type: String,
      default: '',
    },
    tableIndex: {
      type: Number,
      default: 0,
    },
    showLabel: {
      type: Boolean,
      default: true,
    },
  });

  // 值
  const _value = ref<any>();
  const _associatedFormData = ref({});
  const _associatedFormItem = ref<WorkComponent.ComponentConfig>();

  // 键
  const formItemProp = computed(() => {
    if (isNotEmpty(props.tableId)) {
      return props.tableId + '.' + props.tableIndex + '.' + props.formItem.id;
    } else {
      return props.formItem.id;
    }
  });

  /**
   * @description: 是否必填, true-必填
   */
  const _required = computed(() => {
    return props.formItem.props.required;
  });

  /**
   * @description: 校验规则
   */
  const _rules = computed(() => {
    const isRequired = _required.value;
    if (props.mode != 'form') {
      return [];
    }
    return isRequired ? [{ required: true, message: `请输入${props.formItem.title}` }] : [];
  });

  /**
   * @description: 是否隐藏, true-隐藏
   */
  const _hidden = computed(() => {
    let r = false;
    // 解析隐藏条件公式
    if (props.formItem.props.hidden) {
      let expression = props.formItem.props.hidden;
      // 如果是子表中的控件，则需要用到下标
      if (isNotEmpty(props.tableId)) {
        expression = expression.replaceAll('?', props.tableIndex);
      }
      r = evaluateFormula(expression, props.formData);
    }
    // 判断流程节点下该控件是否隐藏
    if (props.formItem.operation && props.formItem.operation.length > 0) {
      r = r || props.formItem.operation[0] == FormPermissionEnum.HIDDEN;
    }
    return r;
  });

  /**
   * @description: 监听表单数据变化
   */
  const _formData = computed(() => {
    return JSON.parse(JSON.stringify(props.formData));
  });

  // 监听关联表单数据变化
  watch(
    () => _formData.value[props.formItem.props.associatedForm.fieldId],
    async (val) => {
      if (
        val &&
        isNotEmpty(val) &&
        isNotEmpty(val.value) &&
        isNotEmpty(props.formItem.props.associatedField)
      ) {
        const code = props.formItem.props.associatedForm.formCode;
        let instance;
        if (isObject(val)) {
          instance = val;
        } else {
          instance = JSON.parse(val);
        }

        await instanceInfoByInstanceIdApi(code, instance.value).then((res: any) => {
          if (res.code === ResultEnum.SUCCESS) {
            _associatedFormData.value = res.data.instanceInfo;
            _value.value = _associatedFormData.value[props.formItem.props.associatedField];
            _associatedFormItem.value = flatFormItems(res.data.formInfo.formItems).find(
              (item) => item.id === props.formItem.props.associatedField,
            );
            if (_associatedFormItem.value) {
              _associatedFormItem.value.props.required = false;
              _associatedFormItem.value.props.readonly = true;
              _associatedFormItem.value.title = props.formItem.title;
            }
          } else {
            _associatedFormData.value = {};
            _value.value = undefined;
            _associatedFormItem.value = undefined;
          }
        });
      } else {
        _associatedFormData.value = {};
        _value.value = undefined;
        _associatedFormItem.value = undefined;
      }
    },
    { immediate: true, deep: true },
  );

  defineExpose({
    _hidden,
  });
</script>
<style scoped lang="scss"></style>
